package com.joshondesign.sdljava.gfx;

import com.joshondesign.sdljava.SDL_Event;
import com.joshondesign.sdljava.SDL_EventMask;
import com.joshondesign.sdljava.SDL_MouseButtonEvent;
import com.joshondesign.sdljava.events.Gestures;
import com.joshondesign.sdljava.events.RawEvents;

public class ButtonNode extends Control {
    protected String text = "";
    private boolean pressed = false;
    protected SColor fillColor = SColor.BLUE;

    public ButtonNode(Scene scene) {
        scene.listen(Trigger.MousePressed().setCallback(new Callback<SDL_Event>(){
            public void call(SDL_Event sdl_event) {
                if(sdl_event.getButton().getState() == 1 &&
                        inside(sdl_event.getButton().getX(), sdl_event.getButton().getY(), x,y,width,height)) {
                    pressed = true;
                }
            }
        }));
        scene.listen(Trigger.MouseReleased().setCallback(new Callback<SDL_Event>() {
            public void call(SDL_Event sdl_event) {
                if(sdl_event.getButton().getState() == 0 && pressed) {
                    pressed = false;
                    Gestures.publish(new RawEvents.RawControlEvent(ButtonNode.this));
                }
            }
        }));
    }

    @Override
    public void draw(GFX gfx) {
        gfx.translate(x,y);

        if(pressed) {
            gfx.setPaint(new SColor(40,80,150));
        } else {
            gfx.setPaint(fillColor);
        }
        gfx.fillRect(0,0,width,height);
        gfx.drawRect(0,0,width,height);

        gfx.setPaint(new SColor(255,255,255));
        gfx.drawString(this.font, text, 50,60);

        gfx.translate(-x,-y);
    }

    public ButtonNode setText(String text) {
        this.text = text;
        return this;
    }

    public ButtonNode setFillColor(SColor fillColor) {
        this.fillColor = fillColor;
        return this;
    }

    public void onAction(Callback<Gestures.ActionEvent> callback) {
        Gestures.listen(Gestures.Action(this),callback);
    }
}
